<?php

class TicketController extends AdminController {

    public function actionIndex() {
        if (isset($_POST['Event']['date'])) {
            //Format date
            $start_date = date('Y-m-d', strtotime($_POST['Event']['date']));
            //Define new Criteria
            $criteria = new CDbCriteria();
            $criteria->with = array('tickets', 'translate');
            $criteria->compare('start_date', $start_date, true);
            $model = Event::model()->findAll($criteria);
            // echo "<pre>";
            // var_dump($model[2]->translate);
            // echo "</pre>";
            // die();
            //Format date
            $start_date = date('d-m-Y', strtotime($start_date));
            $this->render('index', array('model' => $model, 'start_date' => $start_date));
        } else {
            date_default_timezone_set('UTC');
            $date = date('Y-m-d');
            //Define new Criteria
            $criteria = new CDbCriteria();
            $criteria->with = array('tickets', 'translate');
            $criteria->compare('start_date', date('Y-m-d', strtotime($date)), true);
            $model = Event::model()->findAll($criteria);

            //Format dateM  
            $start_date = date('d-m-Y', strtotime($date));
            $this->render('index', array('model' => $model));
        }
    }

    /**
     * <Jason>
     * <Email: pmhai90@gmail.com>
     */
    public function actionPreCreate() {
        $event = new Event();
        $data = $event->getEventActive(STATUS_ACTIVE);
        $this->render('index_event', array(
            'data' => $data
        ));
    }

    /**
     * <Jason>
     * <Email: pmhai90@gmail.com>
     * @param type $event_id
     */
    public function actionCreate($event_id) {
        date_default_timezone_set('UTC');
        $event_id = $_GET['event_id'];
        $user_id = Yii::app()->user->id;

        $event = Event::model()->findByPk($event_id);
        $current_date = date("Y-m-d H:i");
        //Check expired event -- Don't allow create or edit if it's expired
        if ($current_date >= date("Y-m-d H:i", strtotime($event->start_date . $event->start_time))) {
            $message = "Event has been Expired";
            $this->render('create', array('message' => $message));
        } else {
            if ((isset($event) && $event->lock_session == 0 && $event->user_lock == 0) || $event->user_lock == $user_id) {
                $event->lock_session = 1;
                $event->user_lock = $user_id;
                $event->update(array('lock_session', 'user_lock'));

                $model = new Ticket();


                if (isset($_POST['Ticket'])) {

                    for ($i = 1; $i <= count($_POST['Ticket']['seat_map']); $i++) {
                        $query = 'select max(convert(substr(replace(ticket_code," ",""), 18), unsigned integer)) from tickets where event_id=' . $event_id;
                        // $ticket_exist = Ticket::model()->findAllByAttributes(array('event_id' => $event_id),array('order' => 'id DESC','limit' => 1));
                        $ticket_exist = Yii::app()->db->createCommand($query)->queryScalar();
                        $m = new Ticket();
                        foreach ($_POST['Ticket'] as $key => $value) {
                            $a = $i - 1;

                            if ($key != 'fileImage') {
                                $m->$key = $_POST['Ticket'][$key][$a];
                            }
                        }
                        $m->event_id = $_GET['event_id'];
//                    $m->type_of_ticket = $i;
                        // $m->type_of_ticket = 1;
                        if (isset($ticket_exist) && $ticket_exist != null) {
                            // var_dump($ticket_exist);
                            // var_dump($string);die();
                            $continue_number = (int) $ticket_exist + 1;

                            $m->ticket_code = trim($m->event->event_code) . "_TKC-" . $continue_number;
                        } else {
                            $m->ticket_code = trim($m->event->event_code) . "_TKC-" . $i;
                        }

                        $m->date = date('Y-m-d H:i:s');
                        $m->remain_quantity = $m->quantity;
                        $m->created_by = $user_id;
                        $objectFile = NULL;
                        if ($m->seat_map == 1) {
                            //Get Instance Image Upload File
                            $objectFile = CUploadedFile::getInstance($m, 'fileImage[' . $a . ']');

                            //Check object file and rename image.
                            if ($objectFile)
                                $m->fileImage = 'pic_' . $a . '_' . md5(time()) . '.' . $objectFile->getExtensionName();
                        }
                        $m->validate();
                        //Validate success: system will be return none error
                        if (!$m->hasErrors()) {
                            //Upload Seat Map to server
                            if ($objectFile) {
                                $m->pic_seat_map = MyFunctionCustom::savePic($m, $objectFile);
                            }
                            $m->save();
                        } else {
                            echo var_dump($m->getErrors());
                        }
                    }
                    if ($event->user_lock == $user_id) {
                        $link = '';
                        $link .= Yii::app()->getBaseUrl(true) . '/bookingsystem';

                        $event->lock_session = 0;
                        $event->user_lock = 0;
                        $event->update(array('lock_session', 'user_lock'));

                        Yii::app()->user->logout();
                        $this->redirect($link);
                    }
                }
                // die();
                $this->render('create', array(
                    'model' => $model,
                ));
                
            } else {
                Yii::app()->user->setFlash("error", "Event has been using by another user, please try again later!");
                $url = Yii::app()->createAbsoluteUrl('bookingsystem/ticket/precreate');
//            $this->redirect(array('default/index'));
                $this->redirect($url);
            }
        }
    }

    /**
     * <Jason>
     * <Email: pmhai90@gmail.com>
     */
    public function actionUpdate($id) {
//          try{
        date_default_timezone_set('UTC');
        $event_id = $_GET['event_id'];
        $user_id = Yii::app()->user->id;

        $event = Event::model()->findByPk($event_id);
        $link = '';
        $link .= Yii::app()->getBaseUrl(true) . '/bookingsystem';
        $current_date = date("Y-m-d H:i");
        $model = Ticket::model()->findbyPk($id);
       // $model->scenario = "update1";
        if ($current_date > date("Y-m-d H:i", strtotime($event->start_date . $event->start_time))) {
            $message = "Event has been Expired";
            // $model = Ticket::model()->findbyPk($id);

            $this->render('update', array('message' => $message, 'model' => $model));
        } else {
            if ((isset($event) && $event->lock_session == 0 && $event->user_lock == 0) || $event->user_lock == $user_id) {
                $event->lock_session = 1;
                $event->user_lock = $user_id;
                $event->update(array('lock_session', 'user_lock'));

               
                if (isset($_POST['Ticket'])) {
                    $model->attributes = $_POST['Ticket'];
                    
                    $temp_quantity = $this->multiexplode(array(",",".","|",":",";"," "),$_POST['Ticket']['temp_quantity']);
                    $model->temp_quantity = CJSON::encode($temp_quantity);
                    $model->type_of_ticket = $_POST['Ticket']['type_of_ticket'];
                    $model->updated_date = date("Y-m-d H:i");
                    $model->updated_by = $user_id;

                    $objectFile = NULL;
                    if ($model->seat_map == 1) {
                        //Get Instance Image Upload File
                        $objectFile = CUploadedFile::getInstance($model, 'fileImage');
                        //Check object file and rename image.
                        if ($objectFile != null){
                            $model->fileImage = 'pic_' . md5(time()) . '.' . $objectFile->getExtensionName();
                        }
                    }
                    $model->validate();
                    //Validate success: system will be return none error
                    if (!$model->hasErrors()) {
                        //Upload Seat Map to server
                        if ($objectFile != null) {
                            $model->pic_seat_map = MyFunctionCustom::savePic($model, $objectFile);
                        } 
                        $model->save();
                    } else {
                        echo var_dump($model->getErrors());
                    }

                    if ($event->user_lock == $user_id) {

                        $event->lock_session = 0;
                        $event->user_lock = 0;
                        $event->update(array('lock_session', 'user_lock'));

                        Yii::app()->user->logout();
                        $this->redirect($link);
                    }
                }
                $this->render('update', array(
                    'model' => $model,
                ));
            } else {
                $this->redirect($link);
            }
        }
    }

    /**
     * <Jason>
     * <Email: pmhai90@gmail.com>
     * @param type $id
     * @throws CHttpException
     */
    public function actionView() {
        try {
            $this->layout = false;
            $model = Ticket::model()->with('event')->findByPk($_GET['ticket_id']);

            echo $this->render('view', array('model' => $model), true, true);
        } catch (Exception $e) {
            Yii::log("Exception " . print_r($e, true), 'error');
            throw new CHttpException("Exception " . print_r($e, true));
        }
    }

    /**
     * <Jason>
     * <Email: pmhai90@gmail.com>
     * @param type $id
     * @throws CHttpException
     */
    public function loadModel($id) {
        if (!is_numeric($id))
            throw new CHttpException(404, 'The requested page does not exist.');
        try {
            $model = Ticket::model()->with('event', 'create_user', 'update_user')->findByPk($id);
            if ($model === null) {
                Yii::log("The requested page does not exist.");
                throw new CHttpException(404, 'The requested page does not exist.');
            }
            return $model;
        } catch (Exception $e) {
            Yii::log("Exception " . print_r($e, true), 'error');
            throw new CHttpException("Exception " . print_r($e, true));
        }
    }
    public function multiexplode ($delimiters,$string) {

        $ready = str_replace($delimiters, $delimiters[0], $string);
        $launch = explode($delimiters[0], $ready);
        return  $launch;
    }

}

?>